﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FeedReader.Shared;
using FeedReader.Shared.Data;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace MvcFrontEnd.Models
{
    public static class MyFeedExtensions
    {
        public static ViewFeed ParseFeedDataModelMeta(this ViewFeed result, FeedsDataModel feed)
        {
            result.Title = feed.Title;
            result.url = feed.HtmlURL;
            return result;
        }
        public static ViewPost ParsePostDataModel(this ViewPost result, PostsDataModel post, string content){
            result.Title= post.Title;
            result.url=post.URL;
            result.Content=content;
            return result;
        }
        public static ViewPost ParsePostData(this ViewPost result, Post post, string content)
        {
            result.Title = post.Title;
            result.url = "";// TODO: rectify this.
            result.Content = content;
            return result;
        }
    }
    public class ViewPost
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTimeOffset Date{get;set;}
        public string url { get; set; }
    }

    public class ViewFeed
    {
        public string Title { get; set; }
        public string url { get; set; }
        public List<ViewPost> posts { get; set; }
    }
    
    public class FeedRepository
    {
        CloudStorageAccount acc = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        FeedsDataSource feedtable;
        PostsDataSource PostTable;
        BlogIDDataSource blogidsource;
        CloudBlobClient theblobclient;
        CloudBlobContainer postfiles ;

        public FeedRepository()
        {
            feedtable = new FeedsDataSource(acc);
            PostTable = new PostsDataSource(acc);
            blogidsource = new BlogIDDataSource(acc);
            theblobclient = acc.CreateCloudBlobClient();
            postfiles = theblobclient.GetContainerReference(ContainerNameServices.Posts);
        }
        public List<ViewPost> getposts(string id){
           
             List<ViewPost> results = (from PostsDataModel d in PostTable.Select(id)
                           select (new ViewPost()).ParsePostDataModel(d,postfiles.GetBlobReference(d.TheBlobID).DownloadText())).ToList<ViewPost>();
        
            return results;
        }

        public ViewFeed getFeedMeta(string id)
        {
            List<ViewFeed> result= (from d in feedtable.Select(id)
                        select (new ViewFeed()).ParseFeedDataModelMeta(d)).ToList<ViewFeed>();
            return result[0];
        }
    }
}